package com.xiyi.shouxin.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.xiyi.shouxin.dao.user.VideoRepository;
import com.xiyi.shouxin.entity.user.Video;
import com.xiyi.shouxin.entity.user.mapper.VideoMapper;
import com.xiyi.shouxin.exception.CommonException;
import com.xiyi.shouxin.exception.ErrorCode;
import com.xiyi.shouxin.view.pojo.ItemPage;
import com.xiyi.shouxin.view.pojo.VideoView;

@Service
public class VideoService {
    @Autowired
    private VideoRepository videoRepository;

    /*
     * 视频列表
     */
    public ItemPage<VideoView> findVideoList(String name, int page, int size) throws Exception {
        List<VideoView> list = new ArrayList<>();
        List<Video> result = new ArrayList<>();
        int total = 0;
        Sort sort = Sort.by(Direction.DESC, "id");
        result = videoRepository.findByMultiConditionsByPage(name, sort, page, size);
        total = videoRepository.countByMultiConditions(name);
        for (Video video : result) {
            list.add(new VideoView(video));
        }
        return new ItemPage<VideoView>(list, total);
    }

    /*
     * 视频详情
     */
    public VideoView findVideo(Long videoId) throws Exception {
        Video video = videoRepository.findById(videoId, new VideoMapper());
        if (video != null) {
            return new VideoView(video);
        }
        throw new CommonException(ErrorCode.NOTFOUND);
    }

    /*
     * 添加视频
     */
    public VideoView createVideo(Video video) throws Exception {
        if (video == null || !StringUtils.hasText(video.getName())) {
            throw new CommonException(ErrorCode.INVALIDPARAMTER);
        }
        Long id = videoRepository.create(video);
        video.setId(id);
        return new VideoView(video);
    }

    /*
     * 修改视频
     */
    public void updateVideo(Video video) throws Exception {
        if (video == null || video.getId() == null) {
            throw new CommonException(ErrorCode.INVALIDPARAMTER);
        }

        videoRepository.update(video.getId(), video);
    }

    /*
     * 删除视频
     */
    public void delVideos(List<Long> videoIds) throws CommonException {
        if (videoIds == null || videoIds.isEmpty()) {
            return;
        }
        videoRepository.delByIds(videoIds);
    }

}
